﻿namespace Atomic.Plugins.Security.Repositories
{
    using System.Linq;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;

    using Atomic.Caching;
    using Atomic.Extensions;
    using Atomic.Data.AdoNet;

    using Atomic.Modules.Security;
    
    /// <summary>
    /// 用户信息访问器。
    /// </summary>
    public class UserRepository : RepositoryBase, IUserRepository
    {
        /// <summary>
        /// 表名。
        /// </summary>
        private const string TABLE_NAME = "atomic_u_users";

        /// <summary>
        /// 表主键。
        /// </summary>
        private const string TABLE_KEY = "Id";

        /// <summary>
        /// 权限信息访问器。
        /// </summary>
        private readonly IPermissionRepository _permissionRepository = null;

        /// <summary>
        /// 初始化用户信息访问器。
        /// </summary>
        /// <param name="permissionRepository">权限信息访问器。</param>
        public UserRepository(IPermissionRepository permissionRepository)
        {
            this._permissionRepository = permissionRepository;
        }

        /// <summary>
        /// 根据账号获得用户信息。
        /// </summary>
        /// <param name="accountNumber">账号。</param>
        /// <returns>用户信息。</returns>
        public User GetUserByAccountNumber(string accountNumber)
        {
            string sqlWhere = "AccountNumber = @AccountNumber";

            IDataParameter parameters = new SqlParameter("@AccountNumber", accountNumber);

            return this.GetUser(sqlWhere, parameters);
        }

        /// <summary>
        /// 根据用户编号获得用户信息。
        /// </summary>
        /// <param name="id">用户编号。</param>
        /// <returns>用户信息。</returns>
        public User GetUser(long id)
        {
            string sqlWhere = "Id" + id;

            return this.GetUser(sqlWhere);
        }

        /// <summary>
        /// 获得用户信息。
        /// </summary>
        /// <param name="sqlWhere">SQL 条件。</param>
        /// <param name="commandParameters">SQL 参数。</param>
        /// <returns>用户信息。</returns>
        private User GetUser(string sqlWhere, params IDataParameter[] commandParameters)
        {
            User user = null;

            //用户拥有的权限的字符串。
            string userRoles = string.Empty;

            string sql = "SELECT " + TABLE_KEY + ", AccountNumber, Password, Name, Email, Disable, Roles FROM " + TABLE_NAME;

            if (!string.IsNullOrWhiteSpace(sqlWhere))
            {
                sql += " WHERE " + sqlWhere;
            }

            using (IDataReader dataReader = this.DataProvider.SqlQuery(sql, commandParameters))
            {
                if (dataReader.Read())
                {
                    user = new User();
                    user.ChangeCurrentIdentity(dataReader.GetInt32(0));
                    user.Account = new Account(accountNumber: dataReader.GetString(1), password: dataReader.GetString(2));
                    user.Name = dataReader.GetString(3);
                    user.Email = dataReader.GetString(4);
                    user.Disable = dataReader.GetInt32(5) == 0;
                    userRoles = dataReader.GetString(6);
                }
            }

            if (user != null)
            {
                IList<Role> roles = new List<Role>();

                //将“1,3,6,7”格式的角色编号转换成每个数字为一个单位的字符数组，根据这些编号获取对应的角色信息并增加到角色列表里。
                userRoles.Split(',').Where(roleId => roleId.IsNumeric()).ForEach(roleId => roles.Add(this._permissionRepository.GetRole(int.Parse(roleId))));

                user.SetRoles(roles);
            }

            return user;
        }
    }
}